package com.cgy.utils.zookeeper.client;

import com.cgy.utils.netx.client.INetworkClientLibrary;
import com.cgy.utils.netx.config.ClientConfig;
import com.cgy.utils.zookeeper.Zookeepers;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;

/**
 * zookeeper客户端
 * @author CHTK
 */
public class ZookeeperClient implements INetworkClientLibrary<Zookeepers> {

    private Zookeepers zookeepers;

    @Override
    public INetworkClientLibrary<Zookeepers> initial(ClientConfig clientConfig, Object...extConfig) {
        Preconditions.checkArgument(null != clientConfig);
        Preconditions.checkArgument(StringUtils.isNotBlank(clientConfig.getIp()));
        Preconditions.checkArgument(null != clientConfig);

        zookeepers = Zookeepers.builder()
                .ips(clientConfig.getIp())
                .connectionTimeoutMs(clientConfig.getConnectionTimeoutMs())
                .sessionTimeoutMs(clientConfig.getSessionTimeoutMs())
                .build();
        return this;
    }

    @Override
    public INetworkClientLibrary initial(InputStream inputStream) {
        return this;
    }

    @Override
    public INetworkClientLibrary<Zookeepers> connect() throws Exception {
        zookeepers.connect();
        return this;
    }

    @Override
    public void release() throws Exception {
        zookeepers.release();
    }

    @Override
    public Zookeepers getClient() throws Exception {
        return zookeepers;
    }
}
